package main

import (
	"sync"
)

type ConnManager struct {
	conns map[string]*ReceiverConnection
	mutex sync.Mutex
}

func NewConnManager() *ConnManager {
	cm := ConnManager{}
	cm.conns = make(map[string]*ReceiverConnection)
	return &cm
}

func (p *ConnManager) Add(mc *ReceiverConnection) {
	if mc == nil || mc.terminalId == "" || mc.conn == nil {
		return
	}
	p.mutex.Lock()
	defer p.mutex.Unlock()

	p.conns[mc.terminalId] = mc
}

func (p *ConnManager) Delete(code string) {
	if code == "" {
		return
	}
	p.mutex.Lock()
	defer p.mutex.Unlock()

	delete(p.conns, code)
}

func (p *ConnManager) DeleteOld(code, IP string) {
	if code == "" || IP == "" {
		return
	}
	p.mutex.Lock()
	defer p.mutex.Unlock()

	v, ok := p.conns[code]
	if ok && v.ip == IP {
		delete(p.conns, code)
	}
}

func (p *ConnManager) Count() int {
	return len(p.conns)
}

func (p *ConnManager) Get(code string) *ReceiverConnection {
	return p.conns[code]
}
